{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /home/limeng/TensorFlow-Examples/input_data/train-images-idx3-ubyte.gz\n",
      "Extracting /home/limeng/TensorFlow-Examples/input_data/train-labels-idx1-ubyte.gz\n",
      "Extracting /home/limeng/TensorFlow-Examples/input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /home/limeng/TensorFlow-Examples/input_data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/home/limeng/TensorFlow-Examples/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "#init_learning_rate = tf.placeholder(tf.float32)\n",
    "log_dir = '/home/limeng/TensorFlow-Examples/tf_logs'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [],
   "source": [
    "#reshape\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "尝试不同神经元数量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [],
   "source": [
    "# First convolutional layer - maps one grayscale image to 32 feature maps.\n",
    "with tf.name_scope('conv1'):\n",
    "  shape = [5, 5, 1, 32]\n",
    "  #参数初始化-高斯分布\n",
    "  W_conv1 = tf.Variable(tf.truncated_normal(shape, stddev=0.1),\n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "  shape = [32]\n",
    "  b_conv1 = tf.Variable(tf.constant(0.1, shape=shape))\n",
    "  l_conv1 = tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv1\n",
    "  h_conv1 = tf.nn.relu(l_conv1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pooling layer - downsamples by 2X.\n",
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='SAME')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Second convolutional layer -- maps 32 feature maps to 64/32.\n",
    "with tf.name_scope('conv2'):\n",
    "  W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 32], stddev=0.1),\n",
    "                        \n",
    "                        collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "  b_conv2 = tf.Variable(tf.constant(0.1, shape=[32]))\n",
    "  l_conv2 = tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], \n",
    "                         padding='SAME') + b_conv2\n",
    "  h_conv2 = tf.nn.relu(l_conv2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tensor(\"batch_norm_5/batchnorm/add_1:0\", shape=(?, 14, 14, 32), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "#batchnorm layer\n",
    "with tf.name_scope('batch_norm'):\n",
    "    axises = list(range(len(h_conv2.shape) - 1))\n",
    "    batch_mean,batch_var = tf.nn.moments(h_conv2,axises,name='moments')\n",
    "    shift = tf.Variable(tf.constant(\n",
    "            0.0, shape=[h_conv2.shape[-1]]), name='beta', trainable=True)\n",
    "    scale = tf.Variable(tf.constant(\n",
    "            1.0, shape=[h_conv2.shape[-1]]), name='gamma', trainable=True)\n",
    "    epsilon = 1e-3\n",
    "    BN_out = tf.nn.batch_normalization(h_conv2, batch_mean, batch_var, shift, scale, epsilon)\n",
    "    print(BN_out)\n",
    "    relu_BN_maps2 = tf.nn.relu(BN_out)  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tensor(\"pool2_4/MaxPool:0\", shape=(?, 7, 7, 32), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "# Second pooling layer.\n",
    "with tf.name_scope('pool2'):\n",
    "    h_pool2 = tf.nn.max_pool(relu_BN_maps2, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='SAME')\n",
    "    print(h_pool2)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "with tf.name_scope('fc1'):\n",
    "  W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 32, 1024], stddev=0.1),\n",
    "                      \n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "  b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))\n",
    "\n",
    "  h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 32])\n",
    "  h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "with tf.name_scope('fc2'):\n",
    "  W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1),\n",
    "                      collections=[tf.GraphKeys.GLOBAL_VARIABLES,'WEIGHTS'])\n",
    "  b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))\n",
    "\n",
    "  y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "#L2正则化\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection('WEIGHTS')] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "\n",
    "#decay Learning_rate\n",
    "LEARNING_RATE_BASE = 0.01 # 设置初始学习率为0.1\n",
    "LEARNING_RATE_DECAY = 0.95 # 设置学习衰减率为0.99\n",
    "LEARNING_RATE_STEP = mnist.train.num_examples / 100 # 设置喂入多少轮BATCH_SIZE之后更新一次学习率,一般设置为 总样本数/BATCH_SIZE\n",
    "global_step = tf.Variable(0,trainable = False)\n",
    "\n",
    "learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,\n",
    "                                           global_step,\n",
    "                                           LEARNING_RATE_STEP,\n",
    "                                           LEARNING_RATE_DECAY,\n",
    "                                           staircase=True)\n",
    "\n",
    "train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 0.378637, l2_loss: 6176.280762, total loss: 0.810976\n",
      "0.89\n",
      "step 200, entropy loss: 0.286599, l2_loss: 5223.488770, total loss: 0.652243\n",
      "0.9\n",
      "step 300, entropy loss: 0.074242, l2_loss: 4545.786133, total loss: 0.392447\n",
      "0.97\n",
      "step 400, entropy loss: 0.447132, l2_loss: 4013.936279, total loss: 0.728108\n",
      "0.9\n",
      "step 500, entropy loss: 0.104092, l2_loss: 3583.540771, total loss: 0.354940\n",
      "0.98\n",
      "step 600, entropy loss: 0.084138, l2_loss: 3290.338867, total loss: 0.314462\n",
      "0.99\n",
      "step 700, entropy loss: 0.257584, l2_loss: 3032.649902, total loss: 0.469870\n",
      "0.95\n",
      "step 800, entropy loss: 0.247506, l2_loss: 2767.356934, total loss: 0.441221\n",
      "0.95\n",
      "step 900, entropy loss: 0.082097, l2_loss: 2553.131104, total loss: 0.260816\n",
      "0.96\n",
      "step 1000, entropy loss: 0.174225, l2_loss: 2472.716797, total loss: 0.347315\n",
      "0.93\n",
      "0.9625\n",
      "step 1100, entropy loss: 0.068701, l2_loss: 2298.753662, total loss: 0.229614\n",
      "0.98\n",
      "step 1200, entropy loss: 0.013558, l2_loss: 2129.858154, total loss: 0.162648\n",
      "0.99\n",
      "step 1300, entropy loss: 0.129127, l2_loss: 2000.486206, total loss: 0.269161\n",
      "0.96\n",
      "step 1400, entropy loss: 0.086416, l2_loss: 1914.115967, total loss: 0.220404\n",
      "0.99\n",
      "step 1500, entropy loss: 0.101637, l2_loss: 1852.596313, total loss: 0.231319\n",
      "0.97\n",
      "step 1600, entropy loss: 0.081321, l2_loss: 1752.016479, total loss: 0.203962\n",
      "0.98\n",
      "step 1700, entropy loss: 0.059440, l2_loss: 1659.825439, total loss: 0.175627\n",
      "0.98\n",
      "step 1800, entropy loss: 0.098161, l2_loss: 1534.502930, total loss: 0.205576\n",
      "0.97\n",
      "step 1900, entropy loss: 0.027343, l2_loss: 1515.548218, total loss: 0.133431\n",
      "1.0\n",
      "step 2000, entropy loss: 0.065549, l2_loss: 1439.921509, total loss: 0.166343\n",
      "0.98\n",
      "0.9804\n",
      "step 2100, entropy loss: 0.086959, l2_loss: 1377.355347, total loss: 0.183374\n",
      "0.99\n",
      "step 2200, entropy loss: 0.046080, l2_loss: 1343.656860, total loss: 0.140136\n",
      "1.0\n",
      "step 2300, entropy loss: 0.066883, l2_loss: 1323.164307, total loss: 0.159504\n",
      "0.99\n",
      "step 2400, entropy loss: 0.019711, l2_loss: 1268.684937, total loss: 0.108519\n",
      "0.99\n",
      "step 2500, entropy loss: 0.065478, l2_loss: 1200.699585, total loss: 0.149527\n",
      "0.95\n",
      "step 2600, entropy loss: 0.019787, l2_loss: 1168.645020, total loss: 0.101592\n",
      "0.98\n",
      "step 2700, entropy loss: 0.041183, l2_loss: 1131.140381, total loss: 0.120363\n",
      "0.99\n",
      "step 2800, entropy loss: 0.112802, l2_loss: 1106.610229, total loss: 0.190265\n",
      "0.98\n",
      "step 2900, entropy loss: 0.107961, l2_loss: 1103.925415, total loss: 0.185236\n",
      "0.96\n",
      "step 3000, entropy loss: 0.062197, l2_loss: 1071.134888, total loss: 0.137177\n",
      "0.99\n",
      "0.9845\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, #learning_rate , \n",
    "                          keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))\n",
    "writer = tf.summary.FileWriter(log_dir,sess.graph)\n",
    "writer.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test_acc is 0.9897\n"
     ]
    }
   ],
   "source": [
    "  # Test trained model\n",
    "print(\"test_acc is %g\"%sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:1}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
